package com.beyondsoft.dtc.mobile.automation.util;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.io.*;

import javax.imageio.ImageIO;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

@SuppressWarnings("restriction")
public class ImageCompress {
	/**
	 * 描述：
	 *
	 * @param path
	 *            需要压缩的图片路径
	 * @param fileName
	 *            要压缩的图片名称
	 * @param toFileName
	 *            压缩后的图片名称
	 * @param scale
	 *            压缩比例 不能大于1,默认0.5
	 * @param quality
	 *            压缩品质介于0.1~1.0之间
	 * @param width
	 *            压缩后的图片的宽度
	 * @param height
	 *            压缩后的图片的高度 返回值：void
	 */
	public static void imageCompress(String path, String fileName,
			String toFileName, float scale, float quality, int width, int height) {
		try { // 原图路径 原图名称 目标路径 压缩比率0.5 0.75 原图宽度 原图高度
			long start = System.currentTimeMillis();
			Image image = ImageIO.read(new File(path + fileName));
			int imageWidth = image.getWidth(null);
			int imageHeight = image.getHeight(null);
			if (scale > 0.5)
				scale = 0.5f;// 默认压缩比为0.5，压缩比越大，对内存要去越高，可能导致内存溢出
			// 按比例计算出来的压缩比
			float realscale = getRatio(imageWidth, imageHeight, width, height);
			float finalScale = Math.min(scale, realscale);// 取压缩比最小的进行压缩
			imageWidth = (int) (finalScale * imageWidth);
			imageHeight = (int) (finalScale * imageHeight);

			image = image.getScaledInstance(imageWidth, imageHeight,
					Image.SCALE_AREA_AVERAGING);
			// Make a BufferedImage from the Image.
			BufferedImage mBufferedImage = new BufferedImage(imageWidth,
					imageHeight, BufferedImage.TYPE_INT_RGB);
			Graphics2D g2 = mBufferedImage.createGraphics();

			g2.drawImage(image, 0, 0, imageWidth, imageHeight, Color.white,
					null);
			g2.dispose();

			float[] kernelData2 = { -0.125f, -0.125f, -0.125f, -0.125f, 2,
					-0.125f, -0.125f, -0.125f, -0.125f };
			Kernel kernel = new Kernel(3, 3, kernelData2);
			ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
			mBufferedImage = cOp.filter(mBufferedImage, null);

			FileOutputStream out = new FileOutputStream(path + toFileName);
			// JPEGEncodeParam param =
			// encoder.getDefaultJPEGEncodeParam(bufferedImage);
			// param.setQuality(0.9f, true);
			// encoder.setJPEGEncodeParam(param);
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
			JPEGEncodeParam param = encoder
					.getDefaultJPEGEncodeParam(mBufferedImage);
			param.setQuality(quality, true);// 默认0.75
			encoder.setJPEGEncodeParam(param);
			encoder.encode(mBufferedImage);
			out.close();
			long end = System.currentTimeMillis();
		} catch (FileNotFoundException fnf) {
		} catch (IOException ioe) {
			// ioe.printStackTrace();
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {

		}
	}

	public static void imageCompress(String path, String fileName,
			String toFileName, float scale, int width, int height) {

		imageCompress(path, fileName, toFileName, scale, 0.75f, width, height);
	}

	private static float getRatio(int width, int height, int maxWidth,
			int maxHeight) {// 获得压缩比率的方法
		float Ratio = 1.0f;
		float widthRatio;
		float heightRatio;
		widthRatio = (float) maxWidth / width;
		heightRatio = (float) maxHeight / height;
		if (widthRatio < 1.0 || heightRatio < 1.0) {
			Ratio = widthRatio <= heightRatio ? widthRatio : heightRatio;
		}
		return Ratio;
	}

	public static byte[] convertImage2Type(String imageFile, String imageType)
			throws Exception {// 图片格式转换
		File inputFile = new File(imageFile);
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		BufferedImage input = ImageIO.read(inputFile);
		ImageIO.write(input, imageType, output);
		return output.toByteArray();
	}

	public static void convertImage2TypePng(String imageFile, String imageType)
			throws Exception {// 图片格式转换
		File inputFile = new File(imageFile);
		int suffixIndex = imageFile.lastIndexOf(".");
		String suffix = imageFile.substring(suffixIndex + 1);
		if (!"png".equals(suffix)) {// 如果原图片的不是PNG格式的图片
			String fileName = imageFile.substring(0, suffixIndex + 1) + "png";
			File output = new File(fileName);
			BufferedImage input = ImageIO.read(inputFile);
			ImageIO.write(input, imageType, output);
			// 转换后删除原文件
			if (inputFile.exists())
				inputFile.delete();
		}
	}
	//--------------------------------------------------------------------
	public static int compareImage(String imgPath1, String imgPath2) throws FileNotFoundException {
		String[] images = {imgPath1, imgPath2};
		// 分析图片相似度 begin
		String[][] list1 = getPX(images[0]);
		String[][] list2 = getPX(images[1]);
		int xiangsi = 0;
		int busi = 0;
		int i = 0, j = 0;
		for (String[] strings : list1) {
			if ((i + 1) == list1.length) {
				continue;
			}
			for (int m=0; m<strings.length; m++) {
				try {
					String[] value1 = list1[i][j].toString().split(",");
					String[] value2 = list2[i][j].toString().split(",");
					int k = 0;
					for (int n=0; n<value2.length; n++) {
						if (Math.abs(Integer.parseInt(value1[k]) - Integer.parseInt(value2[k])) < 5) {
							xiangsi++;
						} else {
							busi++;
						}
					}
				} catch (RuntimeException e) {
					continue;
				}
				j++;
			}
			i++;
		}
		list1 = getPX(images[1]);
		list2 = getPX(images[0]);
		i = 0;
		j = 0;
		for (String[] strings : list1) {
			if ((i + 1) == list1.length) {
				continue;
			}
			for (int m=0; m<strings.length; m++) {
				try {
					String[] value1 = list1[i][j].toString().split(",");
					String[] value2 = list2[i][j].toString().split(",");
					int k = 0;
					for (int n=0; n<value2.length; n++) {
						if (Math.abs(Integer.parseInt(value1[k]) - Integer.parseInt(value2[k])) < 5) {
							xiangsi++;
						} else {
							busi++;
						}
					}
				} catch (RuntimeException e) {
					continue;
				}
				j++;
			}
			i++;
		}
		String baifen = "";
		try {
			baifen = ((Double.parseDouble(xiangsi + "") / Double.parseDouble((busi + xiangsi) + "")) + "");
			baifen = baifen.substring(baifen.indexOf(".") + 1, baifen.indexOf(".") + 3);
		} catch (Exception e) {
			baifen = "0";
		}
		if (baifen.length() <= 0) {
			baifen = "0";
		}
		if(busi == 0){
			baifen="100";
		}
		return Integer.parseInt(baifen) ;
	}

	public static String[][] getPX(String args) throws FileNotFoundException {
		int[] rgb = new int[3];
		FileInputStream file = new FileInputStream(args);
		BufferedImage bi = null;
		try {
			bi = ImageIO.read(file);
		} catch (Exception e) {
			e.printStackTrace();
		}
		int width = bi.getWidth();
		int height = bi.getHeight();
		int minx = bi.getMinX();
		int miny = bi.getMinY();
		String[][] list = new String[width][height];
		for (int i = minx; i < width; i++) {
			for (int j = miny; j < height; j++) {
				int pixel = bi.getRGB(i, j);
				rgb[0] = (pixel & 0xff0000) >> 16;
				rgb[1] = (pixel & 0xff00) >> 8;
				rgb[2] = (pixel & 0xff);
				list[i][j] = rgb[0] + "," + rgb[1] + "," + rgb[2];
			}
		}
		return list;
	}


	/**
	 * 判断是否为纯色
	 * @param imgPath 图片源
	 * @param percent 纯色百分比，即大于此百分比为同一种颜色则判定为纯色,范围[0-1]
	 * @return
	 * @throws IOException
	 */
	public static boolean isSimpleColorImg(String imgPath,float percent) throws IOException{
		BufferedImage src=ImageIO.read(new File(imgPath));
		int height=src.getHeight();
		int width=src.getWidth();
		int count=0,pixTemp=0,pixel=0;
		for(int i=0;i<width;i++){
			for(int j=0;j<height;j++){
				pixel=src.getRGB(i, j);
				if(pixel==pixTemp) //如果上一个像素点和这个像素点颜色一样的话，就判定为同一种颜色
					count++;
				else
					count=0;
            	if((float)count/(height*width)>=percent) //如果连续相同的像素点大于设定的百分比的话，就判定为是纯色的图片
					return true;
				pixTemp=pixel;
			}
		}
		return false;
	}
}
